﻿using System;
using System.Net;
using System.Net.Sockets;

namespace AviationSimulator.UDP
{
    internal class Transmitter : IDisposable
    {
        private readonly IPEndPoint _localEndPoint;
        private readonly UdpClient _transmitter;

        public Transmitter()
        {
            _transmitter = new UdpClient();
        }

        public Transmitter(IPAddress localHostIp, int localHostPort)
        {
            _localEndPoint = new IPEndPoint(localHostIp, localHostPort);
            _transmitter = new UdpClient(_localEndPoint);
        }

        public void Send(Datagram datagram, string hostName, int port)
        {
            if (_transmitter != null)
            {
                try
                {
                    var message = datagram.ToByteArray();
                    _transmitter.Send(message, message.Length, new IPEndPoint(IPAddress.Parse(hostName), port));
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            else
            {
                throw new ArgumentNullException("UDPClient", "not initialized");
            }
        }

        public void Dispose()
        {
            try
            {
                _transmitter.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}